//创建用户相关的小仓库
import { defineStore } from 'pinia'
//引入接口
import {reqLogin, reqLogout, reqUserInfo} from "@/api/user"
//引入数据类型
import type {loginFormData, loginResponseData, userInfoResponseData} from "@/api/user/type.ts"
import type {UserState} from "@/store/modules/types/type.ts"
//引入操作本地存储的方法
import {SET_TOKEN,GET_TOKEN,REMOVE_TOKEN} from "@/utils/token.ts"
//引入路由（常量）
import {constantRoute} from "@/router/routes.ts";
//创建用户小仓库
const useUserStore = defineStore('User', {
    //小仓库存储数据地方
    state: ():UserState => {
        return {
            token:GET_TOKEN(), //用户唯一标识
            menuRoutes:constantRoute,//仓库生成用户菜单路由
            username:'',//用户名
            avatar:'',//用户头像
        }
    },
    //处理异步|逻辑地方
    actions: {
        async userLogin(data:loginFormData) {
            //调用接口
            const result:loginResponseData = await reqLogin(data)
            if(result.code ===200){
                this.token = result.data
                SET_TOKEN(result.data)
                return  'ok'
            }else{
                return Promise.reject( new Error(result.data))
            }
        },
        async userInfo(){
            let result:userInfoResponseData =await reqUserInfo()
            if(result.code ===200){
                this.username = result.data.name
                this.avatar = result.data.avatar
            }else{
                return Promise.reject( new Error(result.message))
            }
        },
        //退出登录
        async userLogout(){
            let result =await reqLogout()
            if(result.code ===200){
                this.token = ''
                this.username = ''
                this.avatar = ''
                REMOVE_TOKEN()
                return 'ok'
            }else{
                return Promise.reject( new Error(result.message))
            }

        }
    },
    getters: {},
})
//对外暴露小仓库
export default useUserStore
